package com.example.lib_common.base

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.lib_net.BaseResponse
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch

open class BaseViewModel: ViewModel() {
    /**
     * 统一处理流
     */
    fun <M: BaseResponse<T>,T> execute(
        action: Flow<M>,
        onStart:(suspend () -> Unit)? = null,
        onError:(suspend (String) -> Unit)? = null,
        onFinish:(suspend (M) -> Unit)? = null,
    ) = viewModelScope.launch {
        action.onStart {
            onStart?.invoke()
        }.catch { err->
            onError?.invoke(err.message.toString())
        }.collectLatest { //解决背压问题，只收集最新的数据，丢弃旧数据
            if (it.code == 200){
                onFinish?.invoke(it)
            }else{
                onError?.invoke(it.msg)
            }
        }
    }
}

